package com.ruoyi.web.controller.common;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.domain.SysKeyNz;
import com.ruoyi.system.domain.SysUserAccount;
import com.ruoyi.system.mapper.SysKeyNzMapper;
import com.ruoyi.system.mapper.SysUserAccountMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@RestController
@RequestMapping(value = "/noBind")
public class NoBindController {

    @Resource
    private SysUserAccountMapper sysUserAccountMapper;

    @Resource
    private SysKeyNzMapper sysKeyNzMapper;

    @Resource
    private RedisCache redisCache;


    @PostMapping(value = "/noBindKeyInfo")
    private AjaxResult noBindKeyInfo(@RequestBody String jsonData) {
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        String keyNumber = jsonObject.getString("keyNumber");
        String type = jsonObject.getString("type");
        // 判断账号是否存在Redis
        Boolean b = redisCache.hasKey(keyNumber);
        if (b)
            return AjaxResult.error("24小时内,只允许解绑一次,请耐心等待~");
        if (type.equals("1")) {
            // 百里出行逻辑
            String result = noBindBL(keyNumber);
            if (result.equals("解绑成功")) {
                // 存放Redis中 24小时
                redisCache.setCacheObject(keyNumber, 1);
                redisCache.expire(keyNumber, 86400);
                return AjaxResult.success("解绑成功!");
            } else {
                return AjaxResult.error(result);
            }
        } else {
            // 鸡腿逻辑
            String result = noBindJT(keyNumber);
            if (result.equals("解绑成功")) {
                // 存放Redis中 24小时
                redisCache.setCacheObject(keyNumber, 1);
                redisCache.expire(keyNumber, 86400);
                return AjaxResult.success("解绑成功!");
            } else {
                return AjaxResult.error(result);
            }
        }
    }

    /**
     * @Deprecated 百里解绑
     */
    private String noBindBL(String account) {
        SysUserAccount sysUserAccount = sysUserAccountMapper.selectSysUserAccountByAccount(account);
        if (sysUserAccount == null)
            return "账号不存在!";
        sysUserAccountMapper.shutDown(account);
        return "解绑成功";
    }

    private String noBindJT(String keyNumber) {
        // 查询卡密是否存在
        SysKeyNz sysKeyNz = sysKeyNzMapper.selectSysKeyNzByKey(keyNumber);
        if (sysKeyNz == null)
            return "账号不存在!";
        sysKeyNzMapper.noBind(keyNumber);
        return "解绑成功";
    }
}
